/*
 * Created on Apr 4, 2004
 *
 */
package littlecyberwar.control.net;

import java.lang.Thread;
import littlecyberwar.util.*;
import littlecyberwar.ui.*;
import littlecyberwar.model.*;
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.util.*;

/**
 * @author Milton  Soong
 *
 * To change the template for this generated type comment go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
public class OutgoingTask extends Thread implements CmdBackingStore {
	Vector cmdVector;
	ObjectOutputStream oo;
	private static OutgoingTask instance;
	
	public OutgoingTask( OutputStream osIn ){
		cmdVector = new Vector(5);
		try {
			oo = new ObjectOutputStream( osIn );
		} catch ( Exception ex ){
			ex.printStackTrace();
		}
		InternalCmdFacade ic = InternalCmdFacade.getInstance();
		ic.addBackingStore(this);
		instance = this;
	}
	
	public static OutgoingTask getInstance() {
		return ( instance );		
	}
	
	public void run() {
		// first comd into a pipe is always the name 
		Players ownPlayer = Players.getSelf();
		String playerName = ownPlayer.getName();
		
		try {
			oo.writeObject(playerName);
				
		} catch ( Exception ex ){
			ex.printStackTrace();
		}			

		while ( true ){
			try {
				synchronized ( cmdVector ){
					cmdVector.wait();
				}
				
				
				// something in the Vector
				while ( cmdVector.size() > 0 ){
					Command cmd = (Command)cmdVector.remove(0);
					cmd.setPlayerName(playerName);
					oo.writeObject(cmd);
				}
			} catch ( Exception ex ){
				ex.printStackTrace();
			}			
		}
	}
	
	/**
	 * This is always invoked on the event dispatch thread, NOT the outgoing thread
	 */
	public void add( Command cmd ){
		synchronized ( cmdVector ){
			cmdVector.add(cmd);
			cmdVector.notifyAll();
		}
		
	}
	
	public void open( Properties prop ){
	}
	
	public void close(){
	}
}
